﻿(*                  FnSharp              

   Base class library extensions and frameworks aimed 
   specifically at improving F# developers lives!

   Written by: Huw Simpson
   License: Microsoft Public License (Ms-PL) 
   Available at: http://fnsharp.codeplex.com

*)
namespace System.Xml.Linq

    open System
    open FnSharp.Bcl.Xml.LightDsl

    [<AutoOpen>]
    module XElementExtension =
        let private mapName = function
            | Name n -> XName.Get (n)
            | QualifiedName (ns,n) -> XName.Get (n, ns)

        let private mapAttribs (attribs:XmlAttribute list) =
            attribs |> List.map (fun a -> new XAttribute (mapName a.Name, a.Value))
                
        let rec private map (e:XmlElement) =
            match e.Content with
            | Empty -> 
                let content =
                    mapAttribs e.Attributes
                    |> List.map (fun a -> a :> obj)

                new XElement (mapName e.Name, content)
            | Value s -> 
                let content =
                    mapAttribs e.Attributes
                    |> List.map (fun a -> a :> obj)
                    |> List.append ([s :> obj])

                new XElement (mapName e.Name, content)
            | Content c -> 
                let content =
                    mapAttribs e.Attributes
                    |> List.map (fun a -> a :> obj)
                    |> List.append (c |> List.map (fun e -> map (e) :> obj))

                new XElement (mapName e.Name, content)

        module XElement =
            let ofLightDsl (xe:XmlElement) = map xe